from django.shortcuts import render

from django.http import HttpResponseRedirect
from django.urls import reverse
from index.models import *          # 导入所有的数据库模型
from django.db.models import F

# Create your views here.

from django.http import HttpResponse
from django.template import loader  # 导入loader方法
from django.shortcuts import render  # 导入render方法
from django.template import Template, Context  # 调用template、以及上下文处理器方法


# 模板的加载与响应的方式一：需要导入HttpResponse,和loader方法
def test_html(request):
    # 获取模板对象
    t = loader.get_template('index/test.html')
    html = t.render({'name1': '大家好'})  # 以字典形式传递数据并生成html
    return HttpResponse(html)  # HttpResponse方式响应html


# 模板的加载与响应的方式二：导入render方法
def test_123(request):
    # 获取数据库的信息

    def test_hello():
        return '大家好'

    class WebSite(object):
        def __str__(self):
            return '111111111'

    context = {
        "name1": "java",
        "name2": "python",
        "name3": ['小明', '小邓', '小丁'],
        'dict': {'name': '欢乐马', 'gender': 'female', 'age': '18'},
        'func': test_hello,
        'web': WebSite()
    }

    return render(request, 'index/test.html', context)  # 根据字典数据生成动态模板


# M:模型  T:模板  V:视图


def test_if(request):
    dic = {'name': '欢乐臭宝马'}
    return render(request, 'index/test_if.html', dic)


def Hello_MyWeb(request):
    # 调用template()方法生成模板
    t = Template("""
                        {% if web.name == '小东' %}
                            {% if printable %}
                                <h1>Hello 小东</h1>
                            {% else %}
                                <h2>欢迎您下次访问，小东</h2>
                            {% endif %}
                        {% endif %}
                                    """)
    c = Context({'web': {'name': '小东'}, 'printable': False})  # Context必须是字典类型的对象，用来给模板传递数据
    html = t.render(c)
    return HttpResponse(html)


def test_list(request):
    dic = {'list01': [['欢乐马', '学java'], ['伤心马', '学python']]}
    return render(request, 'index/test_list.html', dic)


def test_length(request, id):
    # dic = {'value': 'Django is website'}
    # dic = {'value': [
    #     {'name': 'c语言官网', 'num': 2},
    #     {'name': 'Django官网', 'num': 1},
    #     {'name': 'python官网', 'num': 3},
    # ]}

    # 从数据库获取商品的价格 （进货价） （100元）
    # price = sql 语句
    # dic = {'value': 5}
    dic = {"value": ['python', 'django', 'Flask'], 'list': ['Tonado', 'celery'], 'list2': ['小邓', '小丁', '小宋']}

    return render(request, 'index/test_length.html', dic)


def test_url(request):
    page = {}
    for i in range(10):
        page[i + 1] = i * 25

    dic = {'value': '天生我才必有用', 'page': page}
    return render(request, 'index/test_url.html', dic)


def test(request):
    n1 = '懒洋洋'
    n2 = 200
    return render(request, 'index/test.html', locals())


# 定义子类模板视图函数
def inherit_template(request):
    name = '灰太狼'
    course = ['python', 'django', 'flask']
    return render(request, 'index/inherit_template.html', locals())


# 定义父模版的视图函数
def base_html(request):
    return render(request, 'index/base.html')


# 视图函数
def redict_url(request):
    return render(request, 'index/newTest.html')


# reverse函数实现反向解析重定向到我们想要的所有页面
def test_to_reverse(request):
    # HttpResponseRedirect    可以实现重定向
    return HttpResponseRedirect(reverse('index:model'))


# 登录
# def login(request):
#     pass
    # user =
    # password =
    # 判断
    # if password正确的：
    #     return render(request, '首页.html')
    # else:
    #     HttpResponseRedirect(reverse('登录页面的路由'))


# 使用正则的视图函数
def year_test(request, year):
    print(year)
    dic = {'year': year}
    return render(request, 'index/year_test.html', dic)


# author1 = Author.objects.get(id=6)


# 添加书籍
def add_book(request):
    pass
    # book1 = Book(title='Java', public="电子工业出版社", price="90.00", retail_price="90.00")
    # book2 = Book(title='Python', public="人民邮电工业出版社", price="120.00", retail_price="120.00")
    # book3 = Book(title='Php', public="电子工业出版社", price="79.00", retail_price="80.00")
    # book1.save()
    # book2.save()
    # book3.save()
    # return HttpResponse("添加书籍成功")

    # 添加作者
    Author.objects.create(name="灰太狼", email="9999@163.com")
    Author.objects.create(name="喜洋洋", email="6798@163.com")

    return HttpResponse("添加作者成功")

    # 添加用户信息
    # UserInfo.objects.create(username='123', password='123456')
    # UserInfo.objects.create(username='321', password='123456')
    #
    # return HttpResponse("用户注册成功")


# 查询作者
def select_author(request, name):
    # 查询到一个作者对象
    # value = Author.objects.get(name=name)
    # print(value.name)
    # print(value.email)
    # dic = {'name': value.name, 'email': value.email}

    value = Author.objects.get_or_create(name=name)    # 先查询是否存在，若不存在则新建该实例对象
    # dic = {'name': value.name, 'email': value.email}
    print(value[0])
    print(value[1])
    return HttpResponse("添加成功")
    # return render(request, 'index/select_author.html', dic)


# 原生数据库操作方法，查询数据库,视图函数
def select_books(request):
    # 查询到的books是要给可以遍历的对象
    books = Book.objects.raw("select * from index_book")  # 书写sql语句
    return render(request, "index/allBook.html", locals())


# 增加书籍零售价
def add_price(request):
    # 利用F对象
    # Book.objects.all().update(price=F('price') + 100)  # 获取该列所有值并加20

    # 利用传统的方法实现涨价20元
    # for i in range(1, 7):
    #     book = Book.objects.get(id=i)
    #     book.retail_price += 20
    #     book.save()

    books = Book.objects.all()
    for book in books:
        book.retail_price += 50
        book.save()
    return HttpResponse("价格增加成功")


# 设置cookie
def set_cookie_view(request):
    # 实例化一个响应对象
    resp = HttpResponse()
    # 设置 cookie
    # value = # 加密
    resp.set_cookie("username", "YY", 10000)
    # 将cookie信息响应给浏览器 （客户端）
    return resp


# 获取cookie
def get_cookie_view(request):
    # 获取客户端的cookie
    value = request.COOKIES.get("username")
    return HttpResponse('MY COOKIE is: %s' % value)


# def login (登录视图函数)
    # 进行身份识别：
        # 如果有cookie就对该cookie进行识别(从服务端拿到session 与其进行比较)(直接进入首页)
        # 如果没有cookie 就判断用户名 与 密码(登录页)
    # 判读是否登陆成功
    # 如果登录成功就设置cookie 和 session


# 登录 (设置cookie(浏览器)(存活时间：关闭浏览器)  设置session(服务端)(一直存在))


# 退出登录 (删除服务器的session)

def allbook(request):
    # 查询到的books是要给可以遍历的对象
    books = Book.objects.raw("select * from index_book")  # 书写sql语句
    return render(request, "index/allBook.html", locals())


# 用来显示查询页面
def search_title_form(request):
    return render(request, "index/search_title.html")


# 展示查询结果
# def search_title(request):
    # 得到一个列表
    # title = Book.objects.filter(title=request.GET['title'])
    # 测试展示出版社
    # title[0].pub  表示一个出版社的id(唯一表示一个出版社) (对象)
    # print(title[0].pub.pubName)
    # for i in title:
    #     t = PubName.objects.filter(id=i.pub_id)
    #     print(t[0].pubName)
    # return render(request, 'index/book_list.html', locals())


# 展示查询结果(优化)
def search_title(request):
    # 第一个参数表示获取的值, 第二个参数表示默认值
    if not request.GET.get('title', ''):
        errors = ['输入的书名无效']
        # 在这里使用列表的原因, 是因为随着表单功能的修改可能需要传递多个字段, 这时可能会有多个不同的错误信息需要展示
        return render(request, 'index/search_title.html', locals())
    title = Book.objects.filter(title=request.GET['title'])
    return render(request, 'index/book_list.html', locals())


# 查询展示所有书籍
def book_title(request):
    try:
       all_book = Book.objects.all().order_by('-price')
       if not all_book:
           return HttpResponse("书籍信息表为空， 请录入书籍信息")
    except:
        print("查询出错")
    return render(request, 'index/book_table.html', locals())


# 添加书籍
def add_book(request):
    if request.method == 'GET':
        return render(request, 'index/add_book.html')
    elif request.method == 'POST':
        # 添加书籍
        title = request.POST.get('title')
        if not title:
            return HttpResponse('请给出一个正确的title')
        pub = request.POST.get('pub')
        price = float(request.POST.get('price', '999.99'))    # 999.99默认值可不写
        if not price:
            return HttpResponse('请输入价格')
        try:
            retail_price = float(request.POST.get('retail_price'))
            if not retail_price:
                return HttpResponse('请输入市场价')
        except Exception as e:
            print(e)
        # 判断title是不是已经存在了
        old_book = Book.objects.filter(title=title)
        if old_book:
            return HttpResponse('你输入的书籍系统已经存在 !')
        try:
            pub1 = PubName.objects.get(pubName=str(pub))
            Book.objects.create(title=title, price=price, retail_price=retail_price, pub=pub1)
        except Exception as e:
            print('Add ErrorReason is %s' % (e))
        return HttpResponseRedirect('/index/all_book')   # 如果添加书籍成功就重定向到全部书籍展示的页面
    return HttpResponse('请使用正确Http请求方法 !')


# 更新书籍信息
def update_book(request, book_id):
    # book_id 用来查找书籍
    book_id = int(book_id)
    try:
        book = Book.objects.get(id=book_id)
    except Exception as e:
        return HttpResponse("没有找到任何书籍")
    # 判断get请求还是post请求
    if request.method == 'GET':
        return render(request, 'index/update_book.html', locals())
    elif request.method == 'POST':
        # 获取价格
        price = request.POST.get('price')
        # 获取零售价
        retail_price = request.POST.get('retail_price')
        if not price or not retail_price:
            return HttpResponse("请输入更改的零售价或零售价")
        price = float(price)
        retail_price = float(retail_price)
        # 修改对象的属性值
        book.price = price
        book.retail_price = retail_price
        # 存储更新状态
        book.save()
        # 重定向到所有书籍页面
        return HttpResponseRedirect('/index/all_book')


# 删除书籍
def delete_book(request, book_id):
    book_id = int(book_id)
    try:
        book = Book.objects.get(id=book_id)
    except Exception as e:
        print("get查询出现了异常没有找到数据", e)
        return HttpResponse("这里没有书籍可以被删除")
    if request.method == "GET":
        return render(request, 'index/delete_book.html', locals())
    elif request.method == "POST":
        book.delete()
        return HttpResponseRedirect('/index/all_book')
